<?php
	session_start();
	/**
	* @package admin
	* @desc This php file is used to user details inside the database.
	*/

	// Direct calling check
	if(!isset($_POST['submit']))
		die("Do not call this page directly");
	
	
	if ($_SESSION["role"] != "admin")
	{
		header('Location: ../index.php');
		exit();
	}
	
	
	if($_POST['submit'] == "Cancel")
	{
		$name = $_SESSION['userresults']['name'];
		$email = $_SESSION['userresults']['email'];
		$role = $_SESSION['userresults']['role'];
		
		header("Location: ./userresults.php?name=$name&email=$email&role=$role&submit=Find");
		exit();
	}
	else
	{
		// Make arrays
		$_SESSION["errors"] = array();
		$_SESSION['form'] = array();
	
		$user_id = $_POST["user_id"];
		$user_fname = $_POST["fname"];
		$user_lname = $_POST["lname"];
		$user_email = $_POST["email"];
		$user_role = $_POST["role"];
		
		// Name validation	
		if(!empty($user_fname))
		{
			if (!preg_match('/^[a-zA-Z\s]+$/', $user_fname))
				$_SESSION["errors"]["fname"] = "No numbers allowed";
			else if (strlen($user_fname) > 40)
				$_SESSION["errors"]["fname"] = "Maximum 30 characters";
		}
		else
		{
			$_SESSION["errors"]["fname"] = "Name cannot be empty";
		}
		
		if(!empty($user_lname))
		{
			if (!preg_match('/^[a-zA-Z\s]+$/', $user_lname))
				$_SESSION["errors"]["lname"] = "No numbers allowed";
			else if (strlen($user_lname) > 40)
				$_SESSION["errors"]["lname"] = "Maximum 30 characters";
		}
		else
		{
			$_SESSION["errors"]["lname"] = "Last name cannot be empty";
		}		
			
		// Email validation
		if (!empty($user_email))	
		{
			if (!preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/', $user_email))
				$_SESSION["errors"]["email"] = "Email not a valid format";
			else if (strlen($user_email) > 50)
				$_SESSION["errors"]["email"] = "Maximum 50 characters";
		}
		else
		{
			$_SESSION["errors"]["email"] = "Email is empty";
		}
		
		// If there were any errors, show the page again
		if (count($_SESSION["errors"]))
		{
			header("Location: user.php?action=edit&id=$user_id");
			exit;
		}
		
		unset($_SESSION["errors"]);
		/**
		* @desc This include file connects to the database.
		*/
		require '../includes/connect.inc';
		
		//prepare query
		$user_query = "UPDATE users SET firstname = \"$user_fname\", lastname = \"$user_lname\", email = \"$user_email\", role = \"$user_role\" WHERE user_id = $user_id";
		
		//run query
		mysql_query($user_query, $connection) or die("Could not update user details");
		
		
		//Db close connection
		mysql_close($connection);
		
		header("Location: user.php?action=edit&id=$user_id&result=success");
	}	
?>